import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import numpy as np
import matplotlib.pyplot as plt

# 创建简单的MLP模型
def create_mlp_model(input_dim, hidden_layers=[64, 32], output_dim=1):
    model = Sequential()
    
    # 输入层
    model.add(Dense(hidden_layers[0], activation='relu', input_dim=input_dim))
    
    # 隐藏层
    for units in hidden_layers[1:]:
        model.add(Dense(units, activation='relu'))
    
    # 输出层
    model.add(Dense(output_dim, activation='sigmoid'))
    
    return model

# 示例：手写数字识别
from tensorflow.keras.datasets import mnist

# 加载数据
(X_train, y_train), (X_test, y_test) = mnist.load_data()

# 数据预处理
X_train = X_train.reshape(60000, 784).astype('float32') / 255
X_test = X_test.reshape(10000, 784).astype('float32') / 255

# 创建MLP模型
mlp_model = create_mlp_model(input_dim=784, hidden_layers=[128, 64], output_dim=10)
mlp_model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

# 训练模型
history = mlp_model.fit(X_train, y_train, 
                       epochs=10, 
                       batch_size=32, 
                       validation_split=0.2)

# 评估模型
test_loss, test_accuracy = mlp_model.evaluate(X_test, y_test)
print(f"测试集准确率: {test_accuracy:.4f}")



print('-'*40)

from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten

def create_cnn_model(input_shape=(28, 28, 1)):
    model = Sequential([
        # 第一个卷积块
        Conv2D(32, (3, 3), activation='relu', input_shape=input_shape),
        MaxPooling2D((2, 2)),
        
        # 第二个卷积块
        Conv2D(64, (3, 3), activation='relu'),
        MaxPooling2D((2, 2)),
        
        # 第三个卷积块
        Conv2D(64, (3, 3), activation='relu'),
        
        # 全连接层
        Flatten(),
        Dense(64, activation='relu'),
        Dense(10, activation='softmax')
    ])
    return model

# 示例：手写数字识别
from tensorflow.keras.datasets import mnist

# 加载数据
(X_train, y_train), (X_test, y_test) = mnist.load_data()

# 准备图像数据
X_train_cnn = X_train.reshape(-1, 28, 28, 1)
X_test_cnn = X_test.reshape(-1, 28, 28, 1)

# 创建CNN模型
cnn_model = create_cnn_model()
cnn_model.compile(optimizer='adam', 
                 loss='sparse_categorical_crossentropy', 
                 metrics=['accuracy'])

# 训练CNN
cnn_history = cnn_model.fit(X_train_cnn, y_train, 
                           epochs=10, 
                           batch_size=32, 
                           validation_split=0.2)

X_test_flat = X_test.reshape(X_test.shape[0], -1)

# 比较MLP和CNN性能
mlp_test_loss, mlp_test_acc = mlp_model.evaluate(X_test, y_test)
cnn_test_loss, cnn_test_acc = cnn_model.evaluate(X_test_cnn, y_test)

print(f"MLP测试准确率: {mlp_test_acc:.4f}")
print(f"CNN测试准确率: {cnn_test_acc:.4f}")